package com.lshl.lingshang.http.file;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import okhttp3.RequestBody;

/**
 * Description：
 * Created on 2018/8/16 0016
 * Author : 郭
 */
public class UpLoadFilesUtils {
    /**
     * 返回请求参数 用于retrofit2文件上传
     *
     * @param resourceMap
     * @return
     */
    public static Map<String, RequestBody> getRequestBodyMap(Map<String, Object> resourceMap) {
        Map<String, RequestBody> params = new HashMap<>();
        Iterator iterator = resourceMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            if (entry.getValue() instanceof String) {
                //判断值如果是String的话就直接put进去
                UploadFileRequestBody requestBody = new UploadFileRequestBody((String) entry.getValue());
//                RequestBody body=RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"),(String)entry.getValue());
                params.put((String) entry.getKey(), requestBody);
            } else if (entry.getValue() instanceof File) {
                //判断当前值是单个文件的话就把key设置成服务端所要的参数子端名加文件名，具体格式可以看下面的
                UploadFileRequestBody requestBody = new UploadFileRequestBody((File) entry.getValue());
//                RequestBody body=RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"),(File)entry.getValue());
                params.put((String) entry.getKey() + "\";filename=\"" + ((File) entry.getValue()).getName() + "", requestBody);
            } else if (entry.getValue() instanceof File[]) {
                //判断当前的值是文件数组的话，要把一个个文件拆开再put进去
                File[] files = (File[]) entry.getValue();
                if (files != null && files.length > 0) {
                    for (File f : files) {
//                        RequestBody body=RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"),f);
                        UploadFileRequestBody requestBody = new UploadFileRequestBody(f);
                        params.put((String) entry.getKey() + "\";filename=\"" + f.getName() + "", requestBody);
                    }
                }
            }
        }
        return params;
    }
}
